import { Button, Spin } from 'antd'
import notFound from '@/assets/images/common/404.png'
import noAccess from '@/assets/images/common/403.png'
import { useNavigate } from 'react-router-dom'
import React, { ReactNode, useEffect, useState } from 'react'
import { useGetState } from '@/hooks/useRedux'
import { GlobalInitialState } from '@/redux/slices/global.slice'
import { SpinFCType } from 'antd/lib/spin'
import { RoutePathEnum } from '@/routes/localRouteList'

// 颗粒权限组件
type GranularPermissionType = {
    authId: string | number // 权限ID
    type?: 'button' | 'node' // 按钮权限|节点权限
    children: JSX.Element // 需要控制的内容
}
export function GranularPermission(props: GranularPermissionType) {
    const { authId, type = 'node', children } = props
    const { authGrainList } = useGetState<GlobalInitialState>('global')
    const [isAllowed, setIsAllowed] = useState(false)
    const authList = authGrainList.map((item) => item.path)

    useEffect(() => {
        setIsAllowed(authList.includes(authId))
    }, [authId])

    const element = () => {
        if (type === 'button') {
            return React.cloneElement(children, { disabled: !isAllowed })
        }

        return isAllowed ? children : null
    }

    return element()
}

// loading
export function Loading(props: SpinFCType) {
    return (
        <div className="loading">
            <Spin delay={100} tip="页面加载中..." {...props} />
        </div>
    )
}

// 404
export function NotFound() {
    const navigate = useNavigate()
    return (
        <div className="not-found">
            <img src={notFound} alt="" />
            <p>
                您访问的页面不存在！<span onClick={() => navigate(RoutePathEnum.HomePage)}>返回首页</span>
            </p>
        </div>
    )
}

// 403
export function NoAccess() {
    const navigate = useNavigate()
    return (
        <div className="no-access">
            <img src={noAccess} alt="" />
            <p>
                您没有权限访问，请联系管理员！<span onClick={() => navigate(RoutePathEnum.HomePage)}>返回首页</span>
            </p>
        </div>
    )
}
